package cn.edu.cuit.elena.db;

import java.sql.ResultSet;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import cn.edu.cuit.elena.common.Configuration;
import cn.edu.cuit.elena.common.SackConstants;
import cn.edu.cuit.elena.common.SackConstants.DATABASE;

public class ConnectionProvider
{
    private static int MAX_CONNECTIONS = SackConstants.MAX_CONNECTION_NUM;
    private static ConnectionProvider connectionProvier;

    private Map<Integer, DataSource> dataSources;

    private ConnectionProvider()
    {
        Configuration configuration = Configuration.instance();

        dataSources = new HashMap<Integer, DataSource>();

        for( DATABASE db : SackConstants.DATABASE.values() )
        {
            DataSource datasrDataSource = DataSource.create( configuration );
            dataSources.put( db.id(), datasrDataSource );

            LinkedList<Conn> conns = new LinkedList<ConnectionProvider.Conn>();
            for( int i = 0; i < MAX_CONNECTIONS; i++ )
            {
                Conn conn = new Conn( datasrDataSource );
                conns.add( conn );
            }
        }
    }

    public static ConnectionProvider instance()
    {
        if( connectionProvier == null )
        {
            connectionProvier = new ConnectionProvider();
        }

        return connectionProvier;
    }

    public Conn getConnection( int dataSourceId )
    {
        return ConnectionsForEachdataSource.get( dataSourceId ).pop();
    }

    public Conn getConnection( int dataSourceId, int index )
    {
        return ConnectionsForEachdataSource.get( dataSourceId ).get( index );
    }

    public void returnConnection( Conn conn )
    {
        ConnectionsForEachdataSource.get( conn.getDBCode() ).add( conn );
    }

    public class Conn
    {

        private DataSource dataSourceProvider;

        public Conn(DataSource dataSourceProvider)
        {
            // TODO Auto-generated constructor stub
            this.dataSourceProvider = dataSourceProvider;
        }

        public int getDBCode()
        {
            return dataSourceProvider.getDBCode();
        }

        public ResultSet execute( String... parameters )
        {
            //TODO
            return null;
        };

    }
}
